package model

import (
	"errors"

	"github.com/jinzhu/gorm"
)

// DownloadInfo represents a Download info
type DownloadInfo struct {
	gorm.Model
	Name     string `json:"name"`
	CameraID int64  `json:"cameraid"`
	BeginTs  string `json:"begints"`
	EndTs    string `json:"endts"`
	VmsID    int64  `json:"vmsid"`
	Process  int64  `json:"process"`
}

// AddNewDownload add a new Download
func AddNewDownload(name, beginTs, endTs string, cameraID, vmsID, process int64) error {
	db.Save(&DownloadInfo{
		Name:     name,
		CameraID: cameraID,
		BeginTs:  beginTs,
		EndTs:    endTs,
		VmsID:    vmsID,
		Process:  process,
	})

	return nil

}

// ExistDownloadByName check the Download name is exist or not
func ExistDownloadByName(name string) bool {
	var Download DownloadInfo
	db.Select("id").Where("name = ?", name).First(&Download)
	if Download.ID > 0 {
		return true
	}
	return false
}

// GetDownload get a single Download
func GetDownload(DownloadID string) (*DownloadInfo, error) {
	var Download DownloadInfo
	// SELECT * FROM Download WHERE id = DownloadID;
	db.First(&Download, DownloadID)
	if Download.ID == 0 {
		err := errors.New("no Download found")
		return &DownloadInfo{}, err
	}
	result := DownloadInfo{
		Name:     Download.Name,
		CameraID: Download.CameraID,
		BeginTs:  Download.BeginTs,
		EndTs:    Download.EndTs,
		VmsID:    Download.VmsID,
		Process:  Download.Process,
	}

	return &result, nil
}

// GetDownloadWithCaseID get a single Download
func GetDownloadWithCaseID(caseID int64) ([]DownloadInfo, error) {
	var Download []DownloadInfo

	db.Where("case_id = ?", caseID).Find(&Download)

	if len(Download) == 0 {
		err := errors.New("no Download found")
		return []DownloadInfo{}, err
	}

	return Download, nil
}

// ExistDownloadByID check the id is exist or not
func ExistDownloadByID(ID int) bool {
	var myDownload DownloadInfo
	db.Select("id").Where("id = ?", ID).First(&myDownload)
	if myDownload.ID > 0 {
		return true
	}
	return false
}

// UpdateDownload edit user info
func UpdateDownload(id int, data interface{}) bool {
	db.Model(&DownloadInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteDownload delete the user info from db
func DeleteDownload(id int) bool {
	db.Where("id = ?", id).Delete(&DownloadInfo{})

	return true
}

// GetAllDownloads get the all Downloads info from db
func GetAllDownloads() (result []DownloadInfo, err error) {
	var myDownload []DownloadInfo
	db.Find(&myDownload)

	if len(myDownload) == 0 {
		err = errors.New("no Download found")
		return nil, err
	}
	return myDownload, nil
}
